<script setup>
import { ref, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import axios from 'axios';

const students = ref([]);
const form = ref({
  student: ''
});

// 获取成员列表
const fetchMembers = async () => {
  const orgId = localStorage.getItem('loginId');
  try {
    const res = await axios.get(`http://localhost:8080/orgs/${orgId}/members`);
    if (res.data && res.data.code === 200) {
      students.value = res.data.data || [];
    } else {
      ElMessage.error(res.data && res.data.msg ? res.data.msg : '获取成员失败');
    }
  } catch (error) {
    ElMessage.error('获取成员失败');
  }
};

onMounted(fetchMembers);

const deleteMember = async () => {
  if (!form.value.student) {
    ElMessage.error('请选择要移除的学生');
    return;
  }
  const orgId = localStorage.getItem('loginId');
  ElMessageBox.confirm('确定要移除该成员吗？', '移除确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    students.value = [];
    try {
      const res = await axios.delete(`http://localhost:8080/orgs/${orgId}/members/${form.value.student}`);
      if (res.data && res.data.code === 200) {
        ElMessage.success('成员移除成功');
        fetchMembers();
        form.value.student = '';
      } else {
        ElMessage.error(res.data && res.data.msg ? res.data.msg : '移除失败');
      }
    } catch (error) {
      ElMessage.error('移除失败');
    }
  });
};

const resetForm = () => {
  form.value.student = '';
};
</script>

<template>
  <el-form :model="form" label-width="120px">
    <el-form-item label="选择成员" prop="student">
      <el-select v-model="form.student" placeholder="请选择要移除的成员">
        <el-option
          v-for="student in students"
          :key="student.stuId"
          :label="student.name"
          :value="student.stuId"
        ></el-option>
      </el-select>
    </el-form-item>
    <el-form-item>
      <el-button type="danger" @click="deleteMember">移除成员</el-button>
      <el-button @click="resetForm">重置</el-button>
    </el-form-item>
  </el-form>
</template>